import searchbar from './searchbar.js';
// import searchbar from './searchbar.js';

import urlParser from '../../util/urlParser.js';
import searchEngine from '../../util/searchEngine.js';
import funcs from '../../util/funcs.js';
function showSearchSuggestions(text, input, event) {
  // TODO support search suggestions for other search engines
  if (searchEngine.getCurrent().name !== 'DuckDuckGo') {
    searchbar.reset('searchSuggestions');
    return;
  }

  if (
    searchbar.getResultCount() - searchbar.getResultCount('searchSuggestions') >
    3
  ) {
    searchbar.reset('searchSuggestions');
    return;
  }

  fetch('https://ac.duckduckgo.com/ac/?t=min&q=' + encodeURIComponent(text), {
    cache: 'force-cache',
  })
    .then(function (response) {
      return response.json();
    })
    .then(function (results) {
      searchbar.reset('searchSuggestions');

      if (searchbar.getResultCount() > 3) {
        return;
      }

      if (results) {
        results = results.slice(0, 3);
        results.forEach(function (result) {
          var data = {
            title: result.phrase,
            url: result.phrase,
          };

          if (
            urlParser.isURL(result.phrase) ||
            urlParser.isURLMissingProtocol(result.phrase)
          ) {
            // website suggestions
            data.icon = 'carbon:earth-filled';
          } else {
            // regular search results
            data.icon = 'carbon:search';
          }

          var item = searchbar.addResult('searchSuggestions', data);
        });
      }
    });
}

function initialize() {
  console.log('searchSuggestions initialize-----------------------');
  searchbar.register('searchSuggestions', {
    index: 4,
    trigger: function (text) {
      r=!!text && text.indexOf('!') !== 0 
      console.log(text)
      console.log("searchSuggestions trigger"+r);
      return r;
    },
    showResults: funcs.debounce(showSearchSuggestions, 50),
  });
}

export default { initialize };
